package com.jean.com.retrofittest;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 作者：Administrator on 2016/5/10 22:07
 * 邮箱：154336119@qq.com
 */
public class HttpMethods {
    //public static final String BASE_URL = "https://api.douban.com/v2/movie/";
    public static final String BASE_URL = "http://circle2.huizhuang.com/index/diary/";
    public static final int TIME_OUT = 5;
    public Retrofit mRetrofit;
    private SingInterceptor mSingInterceptor;
    private HttpLoggingInterceptor mHttpLoggingInterceptor;
    //获取单例
    public static  HttpMethods getInstance(){
        return SingletonHolder.INSTANCE;
    }
    //构造方法
    public HttpMethods(){
        initInterceptor();
        OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder();
        httpClientBuilder.addInterceptor(mSingInterceptor).addInterceptor(mHttpLoggingInterceptor);
        mRetrofit = new Retrofit.Builder()
                .client(httpClientBuilder.build())
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
    }
    //在访问HttpMethods时创建单例
    private static class SingletonHolder{
        private static final HttpMethods INSTANCE = new HttpMethods();
    }

    public Retrofit getmRetrofit() {
        return mRetrofit;
    }


    /**
     * 初始化拦截器
     */
    private void initInterceptor(){
        mSingInterceptor = new SingInterceptor();
        mHttpLoggingInterceptor = new HttpLoggingInterceptor();
        mHttpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
    }

    /**
     * request拦截器 - 统一传递参数的接口
     */
    class SingInterceptor implements Interceptor {
        @Override
        public Response intercept(Chain chain) throws IOException {
           Request request = chain.request();
            HttpUrl httpUrl = request.url().newBuilder()
                    .addQueryParameter("token","4545464654566").build();
            request = request.newBuilder().url(httpUrl).build();
            return chain.proceed(request);
        }
    }

}
